<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品计划</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#28a745',
                        secondary: '#f2f2f7',
                        dark: '#333333',
                        light: '#f7f7f7',
                        muted: '#666666',
                        danger: '#dc3545',
                        'primary-light': '#e8f5e9',
                    },
                    fontFamily: {
                        sans: ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 12px rgba(0, 0, 0, 0.05)',
                        'hover': '0 8px 24px rgba(0, 0, 0, 0.12)',
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .transition-height {
                transition: max-height 0.3s ease-in-out;
            }
            .menu-item-active {
                @apply bg-primary-light text-primary font-medium;
            }
            .menu-item-hover {
                @apply hover:bg-primary-light transition-colors duration-200;
            }
            .btn-hover-effect {
                @apply transform hover:scale-[1.02] active:scale-[0.98] transition-transform duration-200;
            }
            .input-focus {
                @apply focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200;
            }
        }
    </style>
    <style>
        /* 顶部导航栏样式 */
        .admin-header {
            background-color: #ffffff;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            height: 56px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            position: sticky;
            top: 0;
            z-Index: 100;
        }

        .admin-header .logo {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .admin-header .header-right {
            display: flex;
            align-items: center;
        }

        .admin-header .user-info {
            margin-right: 20px;
            color: #555;
        }

        .admin-header .user-name {
            margin-right: 10px;
            color: #333;
        }

        .admin-header .logout-btn {
            color: #555;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
        }

        .admin-header .logout-btn:hover {
            background-color: #f8f9fa;
        }

        /* 左侧菜单样式 */
        .admin-sidebar {
            width: 240px;
            background-color: #ffffff;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            height: calc(100vh - 56px);
            position: sticky;
            top: 56px;
            overflow-y: auto;
        }

        .menu-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .menu-item > a {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 20px;
            color: #333;
            text-decoration: none;
            cursor: pointer;
        }

        .menu-item > a:hover {
            background-color: #f8f9fa;
        }

        .menu-item.active > a {
            background-color: #e8f5e9;
            color: #28a745;
        }

        .submenu {
            list-style: none;
            padding: 0;
            margin: 0;
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .submenu li a {
            display: block;
            padding: 10px 20px 10px 40px;
            color: #555;
            text-decoration: none;
        }

        .submenu li a:hover {
            background-color: #f8f9fa;
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: 600;
        }

        .menu-arrow {
            transition: transform 0.2s;
            font-size: 10px;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        /* 响应式样式 */
        @media (max-width: 768px) {
            .admin-sidebar {
                display: none;
                position: fixed;
                z-index: 99;
                width: 240px;
                height: 100vh;
                top: 0;
                left: 0;
            }

            .admin-sidebar.active {
                display: block;
            }

            .mobile-menu-button {
                display: block;
                position: fixed;
                bottom: 20px;
                right: 20px;
                background-color: #28a745;
                color: white;
                width: 50px;
                height: 50px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                z-index: 98;
            }
        }

        @media (min-width: 769px) {
            .mobile-menu-button {
                display: none;
            }
        }
    </style>
</head>
<body class="bg-light text-dark font-sans min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="admin-header">
    <div class="header-left">
        <div class="logo">生产过程管理系统</div>
    </div>
    <div class="header-right">
        <span class="user-info">部门经理</span>
        <span class="user-name">
            <script>
                try {
                    const userInfo = localStorage.getItem('userInfo');
                    const user = JSON.parse(userInfo);
                    document.write(user.name || '未登录');
                } catch (e) {
                    document.write('未登录');
                }
            </script>
        </span>
        <button class="logout-btn" onclick="logout()">退出</button>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
    <ul class="menu-list">
        <li class="menu-item">
            <a href="../homepage/manager_home.html">
                <span class="menu-icon">🏠</span>
                <span class="menu-title">首页</span>
                <span class="menu-arrow"></span>
            </a>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">👥</span>
                <span class="menu-title">人员管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../person/person_list.html">人员列表</a></li>
                <li><a href="../person/person_edit.html">添加人员</a></li>
                <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                <li><a href="../person/schedule.html">查看排班表</a></li>
                <li><a href="../person/schedule_statistics.html">班次统计</a></li>
            </ul>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">📦</span>
                <span class="menu-title">物料管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../material/material_list.html">物料列表</a></li>
                <li><a href="*">物料采购统计</a></li>
            </ul>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">⚙️</span>
                <span class="menu-title">设备管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../device/device_list.html">设备列表</a></li>
                <li><a href="*">设备报修报废统计</a></li>
            </ul>
        </li>
        <li class="menu-item active">
            <a href="javascript:void(0)">
                <span class="menu-icon">📝</span>
                <span class="menu-title">产品管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="product_list.html">产品列表</a></li>
                <li><a href="editproduct_plan.html">编辑产品计划</a></li>
                <li><a href="viewproduct_plan.html" class="active">查看产品计划</a></li>
            </ul>
        </li>
        <li class="menu-item">
            <a href="javascript:void(0)">
                <span class="menu-icon">🏢</span>
                <span class="menu-title">供应商管理</span>
                <span class="menu-arrow"></span>
            </a>
            <ul class="submenu">
                <li><a href="../provider/provider_list.html">供应商列表</a></li>
            </ul>
        </li>
    </ul>
</aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-4 md:p-6">
        <div class="max-w-7xl mx-auto">
            <div class="bg-white rounded-xl shadow-card p-6 mb-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
                    <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-dark mb-4 md:mb-0">产品计划列表</h2>
                    <div class="flex items-center space-x-3">
                        <div class="relative flex-1 max-w-md">
                            <input type="text" id="searchPlanId" placeholder="输入计划ID进行搜索"
                                   class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-200 bg-gray-50 input-focus text-dark placeholder:text-gray-400">
                            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                        </div>
                        <button id="searchButton" class="bg-primary text-white px-6 py-3 rounded-lg shadow-sm btn-hover-effect flex items-center">
                            <i class="fa fa-search mr-2"></i>搜索
                        </button>
                    </div>
                </div>

                <div class="flex justify-end mb-4">
                    <button id="addPlanButton" class="bg-white border border-primary text-primary px-6 py-3 rounded-lg shadow-sm btn-hover-effect flex items-center">
                        <i class="fa fa-plus-circle mr-2"></i>新增计划
                    </button>
                </div>

                <!-- 表格 -->
                <div class="overflow-x-auto">
                    <table id="planTable" class="w-full min-w-[640px] border-collapse">
                        <thead>
                        <tr class="bg-gray-50 text-left">
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600 uppercase tracking-wider rounded-tl-lg">计划ID</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600 uppercase tracking-wider">开始时间</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600 uppercase tracking-wider">结束时间</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600 uppercase tracking-wider">描述</th>
                            <th class="px-6 py-4 text-sm font-semibold text-gray-600 uppercase tracking-wider rounded-tr-lg">操作</th>
                        </tr>
                        </thead>
                        <tbody id="planTableBody">
                        <!-- 数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>

                <!-- 无数据提示 -->
                <div id="noDataMessage" class="hidden py-12 text-center">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                        <i class="fa fa-search text-gray-400 text-2xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-1">找不到该数据</h3>
                    <p class="text-gray-500">请尝试使用其他搜索条件</p>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 移动端菜单按钮 -->
<button id="mobileMenuBtn" class="fixed bottom-6 right-6 bg-primary text-white w-14 h-14 rounded-full shadow-lg flex items-center justify-center z-40 md:hidden btn-hover-effect">
    <i class="fa fa-bars text-xl"></i>
</button>

<!-- 确认删除模态框 -->
<div id="deleteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
        <div class="text-center mb-6">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100 mb-4">
                <i class="fa fa-exclamation-triangle text-red-500 text-2xl"></i>
            </div>
            <h3 class="text-xl font-bold text-gray-900 mb-2">确认删除</h3>
            <p class="text-gray-600">你确定要删除这个计划吗？此操作不可撤销。</p>
        </div>
        <div class="flex space-x-3">
            <button id="cancelDeleteBtn" class="flex-1 bg-gray-100 text-gray-700 px-4 py-3 rounded-lg font-medium btn-hover-effect">取消</button>
            <button id="confirmDeleteBtn" class="flex-1 bg-danger text-white px-4 py-3 rounded-lg font-medium btn-hover-effect">确认删除</button>
        </div>
    </div>
</div>

<script>
    let currentPlanId = null;

    // 菜单展开/收起功能
    document.addEventListener('DOMContentLoaded', function() {


        // 菜单折叠功能
        var menuItems = document.querySelectorAll('.menu-item > a');
    menuItems.forEach(function (item) {
        item.addEventListener('click', function (e) {
            var parent = item.parentElement;
            // 判断是否为可展开的菜单（包含submenu的项）
            if (parent.querySelector('.submenu')) {
                // 只对可展开的菜单阻止默认行为
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            }
            // 对直接链接（如首页）不阻止默认行为，允许跳转
        });
    });

        // 默认展开产品管理菜单
        const productMenuItem = document.querySelector('.menu-item.active');
        if (productMenuItem) {
            const submenu = productMenuItem.querySelector('.submenu');
            const arrow = productMenuItem.querySelector('.menu-arrow');
            submenu.style.maxHeight = submenu.scrollHeight + 'px';
            arrow.style.transform = 'rotate(90deg)';
        }

        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });

        // 修复：正确获取退出按钮元素
        document.querySelector('.logout-btn').addEventListener('click', function() {
            logout();
        });

        // 搜索按钮点击事件
        document.getElementById('searchButton').addEventListener('click', function() {
            const planId = document.getElementById('searchPlanId').value;
            loadPlans(planId);
        });

        // 新增计划按钮点击事件
        document.getElementById('addPlanButton').addEventListener('click', function() {
            window.location.href = 'editproduct_plan.html';
        });

        // 取消删除
        document.getElementById('cancelDeleteBtn').addEventListener('click', function() {
            hideDeleteModal();
        });

        // 确认删除
        document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
            if (currentPlanId) {
                deletePlan(currentPlanId);
                hideDeleteModal();
            }
        });

        // 初始加载数据
        loadPlans();
    });

    // 显示删除确认模态框
    function showDeleteModal(planId) {
        currentPlanId = planId;
        const modal = document.getElementById('deleteModal');
        const modalContent = document.getElementById('modalContent');

        modal.classList.remove('hidden');
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
            modalContent.classList.add('scale-100', 'opacity-100');
        }, 10);
    }

    // 隐藏删除确认模态框
    function hideDeleteModal() {
        const modal = document.getElementById('deleteModal');
        const modalContent = document.getElementById('modalContent');

        modalContent.classList.remove('scale-100', 'opacity-100');
        modalContent.classList.add('scale-95', 'opacity-0');

        setTimeout(() => {
            modal.classList.add('hidden');
        }, 300);
    }

    // 退出登录
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');
            window.location.href = '../../../login.html';
        }
    }

    // 加载计划数据
    function loadPlans(planId = '') {
        const searchUrl = planId ? `http://localhost:8080/api/product_plans/${planId}` : 'http://localhost:8080/api/product_plans';
        fetch(searchUrl)
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('planTableBody');
                const noDataMessage = document.getElementById('noDataMessage');

                tableBody.innerHTML = '';

                if (Array.isArray(data) && data.length > 0) {
                    noDataMessage.classList.add('hidden');
                    data.forEach(plan => {
                        const row = document.createElement('tr');
                        row.className = 'border-b border-gray-100 hover:bg-gray-50 transition-colors duration-150';
                        row.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900">${plan.plan_id}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-600">${plan.start_time}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-600">${plan.end_time}</div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm text-gray-600 max-w-[200px] truncate">${plan.description}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex space-x-2">
                                    <button class="bg-primary text-white px-4 py-2 rounded-lg text-sm btn-hover-effect" onclick="editPlan(${plan.plan_id})">
                                        <i class="fa fa-pencil mr-1"></i>编辑
                                    </button>
                                    <button class="bg-red-50 text-red-600 px-4 py-2 rounded-lg text-sm btn-hover-effect" onclick="showDeleteModal(${plan.plan_id})">
                                        <i class="fa fa-trash mr-1"></i>删除
                                    </button>
                                </div>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                } else {
                    noDataMessage.classList.remove('hidden');
                }
            })
            .catch(error => console.error('Error loading plans:', error));
    }

    // 编辑计划
    function editPlan(plan_id) {
        window.location.href = `editproduct_plan.html?plan_id=${plan_id}`;
    }

    // 删除计划
    function deletePlan(planId) {
        // 先删除关联的详情数据
        fetch(`http://localhost:8080/api/Product_Plan_Details/plan/${planId}`)
            .then(response => response.json())
            .then(details => {
                const deletePromises = details.map(detail => {
                    return fetch(`http://localhost:8080/api/Product_Plan_Details/${detail.detail_id}`, {
                        method: 'DELETE'
                    });
                });

                Promise.all(deletePromises)
                    .then(() => {
                        // 再删除计划数据
                        return fetch(`http://localhost:8080/api/product_plans/${planId}`, {
                            method: 'DELETE'
                        });
                    })
                    .then(() => {
                        // 显示删除成功的提示
                        const toast = document.createElement('div');
                        toast.className = 'fixed top-16 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0';
                        toast.innerHTML = '<i class="fa fa-check-circle mr-2"></i>删除成功';
                        document.body.appendChild(toast);

                        setTimeout(() => {
                            toast.classList.remove('translate-y-[-20px]', 'opacity-0');
                        }, 10);

                        setTimeout(() => {
                            toast.classList.add('translate-y-[-20px]', 'opacity-0');
                            setTimeout(() => {
                                document.body.removeChild(toast);
                            }, 300);
                        }, 3000);

                        // 重新加载数据
                        loadPlans();
                    });
            })
            .catch(error => console.error('Error deleting plan details:', error));
    }
</script>
</body>
</html>